<?php

namespace app\api\controller\v100;

use app\common\controller\Api;

use app\admin\model\Item;
use app\admin\model\Warehouse;
use app\admin\model\out\OutInventoryDetail;
use app\admin\model\out\OutInventory;
use app\admin\model\GoodsItem;
use app\admin\model\GoodsCategory;
use think\Config;
use think\Db;

use app\admin\model\Logistics ;
use app\admin\model\in\InInventory ;
use app\admin\model\in\InInventoryDetail ;
use app\admin\model\inventory\InventoryList ;

/**
 * WMS一件代发
 */
class Smart extends Api {

    protected $noNeedLogin = ['createSaleOrder,getTrackNoByOrder,createItem','itemInventory'];
    protected $noNeedRight = ['*'];

    
    /**
     * 根据产品sku查询剩余库存
     *
     * @ApiTitle    (sku查询剩余库存)
     * @ApiSummary  (查询产品剩余库存,注意:所查询库存不统计未确认的出库单跟未入库上架的库存)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/itemInventory)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="itemSku", type="string", required=true, description="产品的sku(如果为空则查询用户下所有产品库存)")
     * @ApiReturnParams   (name="code", type="string", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'itemsku':'string','itemName':'string','itemInventory':'string','outRecord':{}}", description="扩展数据返回")
     * @ApiReturn   
      ({
    "code": 0,
    "msg": "产品sku查询剩余库存请求成功",
    "time": "1574046004",
    "data": [
        {
            "itemSku": "YF00024355",
            "itemName": "纯棉男士短袖T恤宽松圆领男式",
            "balanceCount": 39
        }
    ]
  })
     */

    public function itemInventory(){
      $data = [];
      // $inventory = [];
      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();
        
        if(!array_key_exists("itemSku",$params)){  //如果不传sku,则查询当前用户下面所有sku的库存

          $goodsItems = GoodsItem::where('ushortid',$user->aid)->select();
          
          foreach($goodsItems as $key=>$value){
            // var_dump($value->inventory);
            if($value->inventory){
              $inventoryItem = [];
              $inventoryItem['itemSku'] =  $value['code'];
              $inventoryItem['itemName'] =  $value['name'];
              $inventoryItem['balanceCount'] = intval($value->inventory['balance_count']);
              array_push($data,$inventoryItem);
            }
          }
          
          $this->success('产品sku查询剩余库存请求成功',$data,0);

        }else{
          $itemSku = $params['itemSku'];
          $goodsItem = GoodsItem::where('code',$itemSku)->find(); //暂未过滤非当前用户的sku
          $goodsId = $goodsItem['id'];
          $goodsName = $goodsItem['name'];
   
          if($goodsId){
            $inventoryItem = [];
            $balance_count = InventoryList::where('goods_id',$goodsId)->value('balance_count');
            $inventoryItem['itemSku'] =  $itemSku;
            $inventoryItem['itemName'] = $goodsName;
            $inventoryItem['balanceCount'] = intval($balance_count);
            
            array_push($data,$inventoryItem);
            $this->success('产品sku查询剩余库存请求成功',$data,0); 
          }else{
           $this->error(sprintf('产品sku:%s不存在!',$itemSku),$data,-1);
          }
        }

      }
    }


     /**
     * 创建商品信息
     *
     * @ApiTitle    (创建商品信息)
     * @ApiSummary  (订单创建的接口 注意:1.商品SKU的唯一性)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/createItem)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   
        (name="productInfo", type="object", sample=
        {\"itemname\":\"string\",
          \"itemsku\":\"string\",
          \"barcode\":\"string\",
          \"source\":\"string\",
          \"beforelong\":\"string\",
          \"beforewidth\":\"string\",
          \"beforehigh\":\"string\",
          \"beforeweight\":\"string\",
          \"afterlong\":\"string\",
          \"afterwidth\":\"string\",
          \"afterhigh\":\"string\",
          \"afterweight\":\"string\",
          \"describe\":\"string\",
          \"customscode\":\"string\",
          \"declareprice\":\"string\",
          \"origincountry\":\"string\",
          \"unique_no\":\"string\",
          \"remark\":\"string\"
        }, description="产品信息")

    * @ApiBody 
     (
       产品列表的对象 productInfo 结构如下:星号字段必填

       {
          \"itemname\":\"*产品名称\",
          \"itemsku\":\"*产品sku\",
          \"barcode\":\"*产品条形码\",
          \"source\":\"*来源\",
          \"beforelong\":\"包装前长\",
          \"beforewidth\":\"包装前宽\",
          \"beforehigh\":\"包装前高\",
          \"beforeweight\":\"包装前重\",
          \"afterlong\":\"包装后长\",
          \"afterwidth\":\"包装后宽\",
          \"afterhigh\":\"包装后高\",
          \"afterweight\":\"包装后重\",
          \"describe\":\"描述\",
          \"customscode\":\"海关编码\",
          \"declareprice\":\"申报价格\",
          \"origincountry\":\"原产地\",
          \"unique_no\":\"产品唯一标识码\",
          \"remark\":\"备注信息\"
       }

     )
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'',
         'message':'返回成功'
        })
     */
    public function createItem(){
      $data = [];

      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();
        $productInfo = $params['productInfo'];
        if(!$productInfo){
          $this->error('缺少参数 productInfo',$data,-1);
          return;
        }
        $productInfo = json_decode($productInfo);

        $itemModel = new Item();
        $condition=[];
        $condition['sku'] = $productInfo->itemsku;
        $condition['uid'] =  $user->aid;
        $checkItem = $itemModel->where($condition)->select();
        if(count($checkItem)>0){
          $this->error('系统中已存在相同的SKU!',$data,-2);
          return;
        }

        Db::startTrans();
        try{
          $data = [];
          $data['uid'] = $user->aid;
          $data['sku'] = $productInfo->itemsku;
          $data['itemname'] = $productInfo->itemname;
          $data['source'] = $productInfo->source;
          $data['beforelong'] = $productInfo->beforelong;
          $data['beforewidth'] = $productInfo->beforewidth;
          $data['beforehigh'] = $productInfo->beforehigh;
          $data['beforeweight'] = $productInfo->beforeweight;
          $data['afterlong'] = $productInfo->afterlong;
          $data['afterwidth'] = $productInfo->afterwidth;
          $data['afterhigh'] = $productInfo->afterhigh;
          $data['afterweight'] = $productInfo->afterweight;
          $data['describe'] = $productInfo->describe;
          $data['customscode'] = $productInfo->customscode;
          $data['declareprice'] = $productInfo->declareprice;
          $data['origincountry'] = $productInfo->origincountry;
          $data['barcode'] = $productInfo->barcode;

          $itemid = $itemModel->save($data);
          if($itemid){
            $itemid = $itemModel->id;
            $goodsId = newId();
            $goodsItemModel = new GoodsItem();
            
            $goodsItemModel->id = $goodsId; //id
            $goodsItemModel->code = $productInfo->itemsku; 
            $goodsItemModel->name = $productInfo->itemname;
            $goodsItemModel->data_org = '#'; //产品全局对后台全局可看

            
            $goodsCategory = new GoodsCategory();
            $category = $goodsCategory->where('code',Config::get('category_code'))->find();

            $goodsItemModel->category_id = $category['id'];
            $goodsItemModel->bar_code = $productInfo->barcode;
            $goodsItemModel->original_sku = $productInfo->itemsku;

            $goodsItemModel->unit_id = '';
            $goodsItemModel->item_id = $itemid;

            //获取当前用户的customeid 

            $goodsItemModel->customer_id = $user->customer_id;
            $goodsItemModel->uuid = $user->id;
            $goodsItemModel->ushortid = $user->aid;
            $goodsItemModel->sale_price = $productInfo->declareprice;

            $goodsItemModel->save();
          }
          

          Db::commit();
          $this->success(sprintf('产品:%s-%s添加成功',$productInfo->itemname,$productInfo->itemsku),[],0);
          return;
      } catch (\think\Exception $e) {
        Db::rollback();
      }

      }
    }


    /**
     * 创建销售订单
     *
     * @ApiTitle    (创建销售出库单)
     * @ApiSummary  (订单创建的接口 注意:1.订单号要唯一性;2.产品SKU必须在商品列表中;3.物流商代码对应法国邮政-无签字(001)，法国邮政-有签字(002),Chronnopost(003),平邮-无追踪(004),平邮-有追踪(005))
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/createSaleOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="warehouseCode", type="string", required=true, description="仓库code 默认1")
     * @ApiParams   (name="orderid", type="string", required=true, description="订单号")
     * @ApiParams   (name="logistic", type="string", required=true, description="物流商")
     * @ApiParams   (name="remark", type="string", required=true, description="备注")
     * @ApiParams   
        (name="orderAddress", type="object", sample="
        {
          'recipientName':'string',
          'firstName':'string',
          'lastName':'string',
          'mobile':'string',
          'company':'string',
          'state':'string',
          'province':'string',
          'city':'string',
          'postcode':'string',
          'addressone':'string',
          'addresstwo':'string'
        }", description="订单的发货信息json对象")
     * @ApiParams   
        (name="orderItem", type="array", sample="
        [{
          'itemsku' : 'string',
          'itemnum : 'number'
        }]", description="订单的产品 数组")
     * @ApiBody 
     (
       订单产品列表的对象 orderItem 结构如下:
       [{
          'itemsku' = '112',
          'itemnum = '申请出库数'
       }]
       
       订单地址的对象 orderAddress 结构如下:
       {
          'recipientName =  '收件人姓名',
          'firstName'= '收件人-名',
          'lastName' = '收件人-姓',
          'mobile = '电话',
          'company = '公司',
          'state = '国家',
          'province = '省份',
          'city = '城市',
          'postcode = '邮编',
          'addressone = '地址1',
          'addresstwo = '地址2'
       }

     )
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   
      ({
         'code':'0',
         'data':'',
         'message':'返回成功'
        })
     */
    public function createSaleOrder(){
      $data = [];

      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();

        if(!isset($params['orderid'])){
          $this->error(sprintf('参数orderid缺少'),[],-1);
          return;
        }
        if(!isset($params['orderAddress'])){
          $this->error(sprintf('参数orderAddress缺少'),[],-1);
          return;
        }
        
        if(!isset($params['orderItem'])){
          $this->error(sprintf('参数orderItem缺少'),[],-1);
          return;
        }

        $remark = "";
        if(isset($params['remark'])){
          $remark = $params['remark'];
        }

        $firstName = ""; //名
        if(isset($params['firstName'])){
          $firstName = $params['firstName'];
        }

        $lastName = "";//姓
        if(isset($params['lastName'])){
          $lastName = $params['lastName'];
        }

        $logistic = "";//发货物流商
        if(array_key_exists('logistic',$params)){
          $logistic = $params['logistic'];
        }

        $orderid = $params['orderid'];
        $orderInfo = $params['orderItem'];
        $orderAddress = $params['orderAddress'];
        $warehouse_code = "1";//$params['warehouse_code'];

        $warehouseModel = new Warehouse();
        $warehouseId = $warehouseModel->where(['code'=>$warehouse_code])->column('id')[0];

        $outInventoryModel = new OutInventory();
        

        //校验订单号是否重复
        $orderList = $outInventoryModel->where('orderid',$orderid)->select();
        if(count($orderList)>0){
          $this->error(sprintf('订单号:%s,系统中已存在!',$orderid),[],-1);
          return;
        }

        //校验产品是否存在
        Db::startTrans();
        try {
          $inData = [];
          $inData['warehouse_code'] = $warehouse_code;
          $inData['warehouseid'] = $warehouseId;
          $inData['remark'] = $remark;
          $inData['orderid'] = $params['orderid'];
          $inData['logistic_code'] = $logistic;
          // $test =   System.currentTimeMillis();
          // $time_uniq =  date('Ymd H:i:s').getTime();
          $outOrderId = 'OUTA'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 10), 1))), 0, 8);
          $inData['outorderid'] = $outOrderId;
          $inData['uid'] = $this->auth->aid;

          $outInventoryModel = new OutInventory();
          $result = $outInventoryModel->save($inData);

          $mainid = $outInventoryModel::getLastInsID();

          if($result){

            $orderInfo = (array)json_decode($orderInfo, true);
            $orderAddress = (array)json_decode($orderAddress, true);

            foreach($orderInfo as $key=>$value){
              $data = [];
              $OutInventoryDetail = new OutInventoryDetail();

              $data['id'] = \newId();
              $data['itemsku'] = $value['itemsku'];

              //通过sku查询产品名称
              $itemModel = new Item();
              $goodsItemModel = new GoodsItem();
              $itemRecord = $itemModel->where(["uid"=>$user['aid'],"sku"=>$value['itemsku']])->find();
              
              if(empty($itemRecord)){
                Db::rollback();
                $this->error(sprintf('产品SKU:%s,系统中不存在,无法销售出库!',$value['itemsku']),[],-1);
                return;
              }

              $itemnum = intval($value['itemnum']);
              if($itemnum<=0){
                Db::rollback();
                $this->error(sprintf('产品SKU:%s,出库数量非法!',$value['itemsku']),[],-1);
                return;
              }

              $goodsId = $goodsItemModel->where(["ushortid"=>$user['aid'],"code"=>$value['itemsku']])->value('id');
              $data['itemid'] = $itemRecord['id'];
              $data['itemname'] = $itemRecord['itemname'];

              $data['goods_id'] = $goodsId;

              $data['orderid'] = $orderid;//关联的平台订单号
              $data['goods_count'] = $itemnum; //申请出库数
              $data['sw_count'] = 0; //已出库数
              $data['left_count'] = $itemnum; //未出库数

              $data['outid'] = $mainid;
              $data['out_orderno'] = $outOrderId;
              $data['warehouseid'] = $warehouseId;
              $data['warehouse_code'] = $warehouse_code;

              $data['recipients']= array_key_exists('recipientName',$orderAddress)?$orderAddress['recipientName']:'' ;
              $data['first_name']= array_key_exists('firstName',$orderAddress)?$orderAddress['firstName']:'' ;
              $data['last_name']= array_key_exists('lastName',$orderAddress)?$orderAddress['lastName']:'';
              $data['mobile']= $orderAddress['mobile'];
              $data['company']= $orderAddress['company'];
              $data['state']= $orderAddress['state'];
              $data['province']= $orderAddress['province'];
              $data['city']= $orderAddress['city'];
              $data['postcode']= $orderAddress['postcode'];
              $data['addressone']= $orderAddress['addressone'];
              $data['addresstwo']= $orderAddress['addresstwo'];
              $rsDetail = $OutInventoryDetail->save($data);
            }
          }
        }catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error($e->getMessage());
        }

        Db::commit();
        $this->success('创建销售订单成功',$data,0);
      }        
  }


    /**
     * 根据订单号查询追踪码
     *
     * @ApiTitle    (订单号获取追踪码)
     * @ApiSummary  (需传入有效的订单号)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/getTrackNoByOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="orderid", type="string", required=true, description="订单编号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'{
           trackNo:'123456',
           'uniqueNo':'123456'
         }',
         'msg':'返回成功'
        })
     */
  public function getTrackNoByOrder(){

    if($this->request->isPost()){
      $params = $this->request->post();

      if(!isset($params['orderid'])){
        $this->error(sprintf('参数orderid缺少'),[],-1);
        return;
      }

      $orderid =  $params['orderid'];
      if(!$orderid){
        $this->error(sprintf('请传入订单编号!'),[],-1);
      }

      $inventoryModel = new OutInventory();
      $outInventory = $inventoryModel->where(['orderid'=>$orderid])->find();
    
      if(!$outInventory){
        $data = [];
        $this->error(sprintf('订单编号:%s 不存在出库单!',$orderid),$data,-1);
        exit();
      }else{
        $data = [];
        
        $data['outorderId'] = $outInventory['outorderid'];
        
        $products = [];

        //暂时出库单跟产品一对一的关系
        $productItem = [];

        $outInventoryDetailModel = new OutInventoryDetail();
        $outInventoryDetaiInfo = $outInventoryDetailModel->where(['out_orderno'=>$outInventory['outorderid']])->select();

        // foreach($InventoryItemInfo as $key=>$value){

        $productItem['trackorderNo'] = $outInventory['trackorderid'];
        $productItem['orderid'] = $outInventory['orderid'];

        $items =[];
        foreach($outInventoryDetaiInfo as $key=>$value){
          $item = [];
          $item['sku']=$value['itemsku'];
          $item['skuName']=$value['itemname'];
          $item['uniqueNo'] = $value['unique_no'];
          $items[] = $item;
        }

        $productItem['recipients'] = $outInventoryDetaiInfo[0]['recipients'];
        $productItem['mobile'] = $outInventoryDetaiInfo[0]['mobile'];
        $productItem['company'] = $outInventoryDetaiInfo[0]['company'];
        $productItem['state'] = $outInventoryDetaiInfo[0]['state'];
        $productItem['province'] = $outInventoryDetaiInfo[0]['province'];
        $productItem['city'] = $outInventoryDetaiInfo[0]['city'];
        $productItem['postcode'] = $outInventoryDetaiInfo[0]['postcode'];
        $productItem['addressone'] = $outInventoryDetaiInfo[0]['addressone'];
        $productItem['addresstwo'] = $outInventoryDetaiInfo[0]['addresstwo'];
       
        $productItem['items']= $items;

        
        $productItem['shipTime'] = '';//发货时间
        $productItem['logistics'] = '';//物流商
        
        $data['product'] = $productItem;
        $this->success('订单关联信息请求成功',$data,0);
      }
    } 
  }

    /**
     * 创建入库单
     *
     * @ApiTitle    (创建入库单)
     * @ApiSummary  (需传入有效的产品SKU)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/createInBoundOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="remark", type="string", required=true, description="备注")
     * @ApiParams   (name="trackorderid", type="string", required=true, description="追踪号")
     * @ApiParams   (name="boxnum", type="string", required=true, description="箱数--默认一箱")
     * @ApiParams   
        (name="items", type="array", sample="
        [{
          'itemsku' : 'string',
          'itemnum : 'number',
          'boxno : 'number'
        }]", description="需入库的产品 数组")
    * @ApiBody 
     (
       产品列表的对象 items 结构如下:
       [{
          'itemsku' = '112',
          'itemnum' = '申请出库数'
          'boxno' = '箱号'
       }]
     )
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'{
           
         }',
         'msg':'返回成功'
        })
     */
    public function createInBoundOrder(){
      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();

        if(!isset($params['items'])){
          $this->error(sprintf('参数items缺少'),[],-1);
          return;
        }

        $boxnum = 1;
        if(isset($params['boxnum'])){
          $boxnum = intval($params['boxnum']);
        }

        $trackorderid = '';
        if(isset($params['trackorderid'])){
          $trackorderid = intval($params['trackorderid']);
        }

        $remark = '';
        if(isset($params['remark'])){
          $remark = intval($params['remark']);
        }

        $itemInfo = $params['items'];
        $itemList = (array)json_decode($itemInfo, true);

        $warehouse_code = "1";//$params['warehouse_code'];

        $warehouseModel = new Warehouse();
        $warehouseId = $warehouseModel->where(['code'=>$warehouse_code])->column('id')[0];
        $outInventoryModel = new Ininventory();
       
        Db::startTrans();

        try {
          $inData['warehouseid'] = $warehouseId;
          $inData['warehouse_code'] = $warehouse_code;
          $inData['remark'] = $remark;
          $inorderid =  'IN'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
          $inData['inorderid'] =$inorderid;
          $inData['uid'] = $user->aid;
          $inData['boxcount'] = $boxnum;
          $inData['trackorderid'] = $trackorderid;
          $result = $outInventoryModel->save($inData);
          $inid = $outInventoryModel->getLastInsID();
        
          foreach($itemList as $key=>$value){

            $itemModel = new Item();
            $itemRecord = $itemModel->where(["uid"=>$user['aid'],"sku"=>$value['itemsku']])->find();
            
            if(empty($itemRecord)){
              Db::rollback();
              $this->error(sprintf('产品SKU:%s,系统中不存在,无法销售入库!',$value['itemsku']),[],-1);
              return;
            }

            $inDetailModel = new InInventoryDetail;
            $detailData = [];
            $detailData['itemsku'] = $value['itemsku'];
            $detailData['itemid'] = $itemRecord['id'];
            $detailData['itemname'] = $itemRecord['itemname'];
            $detailData['goods_count'] = intval($value['itemnum']);
            $detailData['left_count'] = intval($value['itemnum']);
            $detailData['inid'] = $inid;
            $detailData['id'] = newId();
            $detailData['orderId'] = $inorderid;
            $detailData['warehouseid'] = $warehouseId;
            $detailData['warehouse_code'] = $warehouse_code;
            $detailData['inBoxNo'] = $value['boxno'];//入库的箱号
            $rsDetail = $inDetailModel->save($detailData);
          }

          Db::commit();
          $this->success('创建入库申请成功,请等待审核入库!',[],0);

        } catch (\think\exception\PDOException $e) {
          $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error($e->getMessage());
        }

      }

    }


    
    /**
     * 出库申请单查询
     *
     * @ApiTitle    (出库申请单列表)
     * @ApiSummary  (查询出库申请单的列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/queryOutApply)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="string", required=false, description="页数")
     * @ApiParams   (name="pageSize", type="string", required=false, description="每页条数")
     * @ApiParams   (name="outApplyNo", type="string", required=false, description="出库单号")
     * @ApiParams   (name="platformOrderId", type="string", required=false, description="平台订单编号")
     * @ApiParams   (name="createTime", type="string", required=false, description="创建时间")
     * @ApiParams   (name="status", type="string", required=false, description="状态 1-待审核 1000-已审核 2001-取消 3000-已出库")
     
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'code':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'{
          
             "total": 1,
              "rows": [
                  {
                      "outorderid": "OUT2019070497525298",
                      "logistics": "",
                      "provider": "",
                      "trackorderid": "",
                      "actualcount": 0,
                      "count": 0,
                      "status": 2001,
                      "warehouseid": "1",
                      "remark": "ttt",
                      "file": "",
                      "orderid": "7757885859859",
                      "create_time": "2019-07-05 15:43:22",
                      "update_time": "2019-07-05 15:43:22",
                      "warehouse_code": "1",
                      "pay_status": null,
                      "logistic_code": null,
                      "weight": null,
                      "fee": null,
                      "logistic": null,
                      "items": [
                          {
                              "itemname": "lining",
                              "itemsku": "S231312321312312",
                              "goodsCount": 1
                          }
                      ]
                  }

         }',
         'msg':'返回成功'
        })
     */
    public function queryOutApply(){
      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();

        $page = 1;
        if(isset($params['page'])){
          $page = intval($params['page']);
        }

        $pageSize = 10;
        if(isset($params['pageSize'])){
          $pageSize = intval($params['pageSize']);
        }

        $condition = "uid=".$user['aid'];
        if(isset($params['outApplyNo'])){
          $outApplyNo = $params['outApplyNo'];
          $condition = $condition." and outorderid= '".$outApplyNo."'";
        }

        if(isset($params['createTime'])){
          $createTime = $params['createTime'];
          $condition = $condition." and create_time= '".$createTime."'";
        }

        if(isset($params['status'])){
          $status = $params['status'];
          $condition = $condition." and status= ".$status;
        }


        $outInventoryModel = new OutInventory();
        $total = $outInventoryModel->where($condition)->order('create_time desc')->count();

        if($page==1){
          $offset = 0;
        }else{
          $offset = $page*$pageSize;
        }

        $field = ['outorderid','logistics','provider','trackorderid','actualcount','count','status','remark','file','orderid','create_time','update_time',
                  'warehouse_code','pay_status','logistic_code','weight','fee','logistic'];
        
        $list = $outInventoryModel->field($field)->where($condition)
            ->order('create_time desc')
            ->limit($offset, $pageSize)
            ->select();

        $list = collection($list)->toArray();

        foreach($list as $key=>$value){
          $list[$key]['logistic'] = Logistics::where('logistics_code',$value['logistic_code'])->value('logistics_name');
        }


        foreach ($list as $key => $value){
            $items = $this->getOutItemsNew($value['outorderid']);

            $itemArray = Array();
            foreach($items as $subkey=>$subvalue){
              $itemArrayTemp =  Array();
              $itemArrayTemp['itemname'] = $subvalue['itemname'];
              $itemArrayTemp['itemsku'] = $subvalue['itemsku'];
              $itemArrayTemp['goodsCount'] = $subvalue['goods_count'];
              $itemArray[] = $itemArrayTemp;
            }

            $list[$key]['items'] = $itemArray;
        }
        $result = array("total" => $total, "rows" => $list);

        $this->success('请求成功',$result,0);
        // return json($result);
      }
    }


    /**
     * 入库申请单查询
     *
     * @ApiTitle    (入库申请单列表)
     * @ApiSummary  (查询入库申请单的列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/queryInApply)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="string", required=false, description="页数")
     * @ApiParams   (name="pageSize", type="string", required=false, description="每页条数")
     * @ApiParams   (name="inApplyNo", type="string", required=false, description="入库申请单号")
     * @ApiParams   (name="trackId", type="string", required=false, description="物流追踪号")
     * @ApiParams   (name="createTime", type="string", required=false, description="创建时间")
     * @ApiParams   (name="status", type="string", required=false, description="状态 1-待审核 1000-已审核 2000-部分入库  2001-已取消 3000-已入库")
     
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'code':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'{
          
            "total": 1,
            "rows": [
            {
                "inorderid": "IN2020031056979799",
                "trackorderid": "",
                "actualcount": 0,
                "count": 0,
                "status": 1,
                "warehouseid": "17A72FFA-B3F3-11E4-9DEA-782BCBD7746B",
                "remark": "",
                "boxcount": 1,
                "create_time": "2020-03-10 17:18:48",
                "update_time": "2020-03-10 17:18:48",
                "warehouse_code": "1",
                "items": [
                    {
                        "itemname": "X 儿童用品",
                        "itemsku": "11090",
                        "goodsCount": 1,
                        "actCount": null
                    }
                ]
            },
        ]
            

         }',
         'msg':'返回成功'
        })
     */

    public function queryInApply(){
      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();

        $page = 1;
        if(isset($params['page'])){
          $page = intval($params['page']);
        }

        $pageSize = 10;
        if(isset($params['pageSize'])){
          $pageSize = intval($params['pageSize']);
        }

        $condition = "uid=".$user['aid'];
        if(isset($params['inApplyNo'])){
          $inApplyNo = $params['inApplyNo'];
          $condition = $condition." and inorderid= '".$inApplyNo."'";
        }

        if(isset($params['createTime'])){
          $createTime = $params['createTime'];
          $condition = $condition." and create_time= '".$createTime."'";
        }

        if(isset($params['trackId'])){
          $trackId = $params['trackId'];
          $condition = $condition." and trackorderid= '".$trackId."'";
        }

        if(isset($params['status'])){
          $status = $params['status'];
          $condition = $condition." and status= ".$status;
        }


        $inInventoryModel = new InInventory();
        $total = $inInventoryModel->where($condition)->order('create_time desc')->count();

        if($page==1){
          $offset = 0;
        }else{
          $offset = $page*$pageSize;
        }

        $field = ['inorderid','trackorderid','actualcount','count','status','warehouseid','remark','create_time','update_time','warehouse_code','boxcount'];
        
        $list = $inInventoryModel->field($field)->where($condition)
            ->order('create_time desc')
            ->limit($offset, $pageSize)
            ->select();

        $list = collection($list)->toArray();



        foreach ($list as $key => $value){
            $items = $this->getInItemsNew($value['inorderid']);

            $itemArray = Array();
            foreach($items as $subkey=>$subvalue){
              $itemArrayTemp =  Array();
              $itemArrayTemp['itemname'] = $subvalue['itemname'];
              $itemArrayTemp['itemsku'] = $subvalue['itemsku'];
              $itemArrayTemp['goodsCount'] = $subvalue['goods_count'];
              $itemArrayTemp['actCount'] = $subvalue['pw_count'];//实际入库数
              $itemArray[] = $itemArrayTemp;
            }
            $list[$key]['items'] = $itemArray;
        }
        $result = array("total" => $total, "rows" => $list);

        $this->success('请求成功',$result,0);
        // return json($result);
      }
    }


    /**
     * 取消出库单
     *
     * @ApiTitle    (出库申请取消)
     * @ApiSummary  (取消/拦截出库申请)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/cancelOutApply)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="outApplyNo", type="string", required=true, description="出库申请单号")
     
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'code':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'{

         }',
         'msg':'返回成功'
        })
     */
    public function cancelOutApply(){
      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();

        $outApplyNo = "";
        if(isset($params['outApplyNo'])){
          $outApplyNo = $params['outApplyNo'];
          $this->error('缺少取消的出库申请单号!',[],-1);
          return;
        }


        $outInventory = OutInventory::get(['outorderid' => $outApplyNo]);

        if($outInventory==null){
          $this->error('对应的出库申请单号不存在!',[],-1);
          return;
        }

        if($outInventory['status']==2001){
          $this->error('当前出库申请单已取消,无须再次取消!',[],-1);
          return; 
        }

        if($outInventory['status']!=1){
          $this->error('非待审核状态下的出库单不可取消,紧急情况直接联系仓库!',[],-1);
          return; 
        }
        $outInventory->status = 2001;
        $outInventory->save();

        // $outInventoryModel->save([
        //   'status'  => '2001',
        // ],['outorderid' => $outApplyNo]);

        $this->success('取消出库申请成功!',[],0);
        // return json($result);
      }
    }

    /**
     * 取消入库申请单
     *
     * @ApiTitle    (入库申请取消)
     * @ApiSummary  (查询出库申请单的列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v100.smart/cancelInApply)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="inApplyNo", type="string", required=true, description="入库申请单号 与 物流单号 二选一")
     * @ApiParams   (name="trackid", type="string", required=false, description="物流单号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="message", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'code':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'0',
         'data':'{

         }',
         'msg':'返回成功'
        })
     */
    public function cancelInApply(){
      if($this->request->isPost()){
        $params = $this->request->post();
        $user = $this->auth->getUser();

        $inApplyNo = "";
        $updateCondition = [];
        if(isset($params['inApplyNo'])){
          $inApplyNo = $params['inApplyNo'];
          $updateCondition['inorderid'] = $inApplyNo;
        }

        $trackid = "";
        if(isset($params['trackid'])){
          $trackid = $params['trackid'];
          $updateCondition['trackorderid'] = $trackid;
        }

        if(strlen($trackid)==0 && strlen($inApplyNo)==0){
          $this->error('入库申请单号 与 物流单号 二选一!',[],-1);
          return;
        }

        // $inInventoryModel = new InInventory();

        $inInventory = InInventory::get($updateCondition);

        if($inInventory==null){
          $this->error('对应的入库申请单号或者物流单号不存在!',[],-1);
          return;
        }

        if($inInventory['status']==2001){
          $this->error('当前入库申请单已取消,无须再次取消!',[],-1);
          return; 
        }

        if($inInventory['status']!=1){
          $this->error('非待审核状态下的入库单不可取消,紧急情况直接联系仓库!',[],-1);
          return; 
        }
        $inInventory->status = 2001;
        $inInventory->save();

        $this->success('取消入库申请成功!',[],0);
        // return json($result);
      }
    }

    private function getOutItemsNew($outorderid){
      $OutInventoryDetailModel = new OutInventoryDetail();
      $outDetail = $OutInventoryDetailModel->where(['out_orderno'=>$outorderid])->select();
      return $outDetail;
    }

    private function getInItemsNew($inorderid){
      $inInventoryDetailModel = new InInventoryDetail();
      $inDetail = $inInventoryDetailModel->where(['orderid'=>$inorderid])->select();
      return $inDetail;
    }

    

}
